package com.fxm.service.impl;

import com.fxm.dao.UserMapper;
import com.fxm.domain.User;
import com.fxm.returns.RespCode;
import com.fxm.returns.RespEntity;
import com.fxm.service.UserService;
import com.fxm.vo.param.IntegralParam;
import com.fxm.vo.param.OpenParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author fxm
 * @since 2020-12-30
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public RespEntity<User> getUserByOpenId(OpenParam openParam) {
        if (Objects.isNull(openParam)) {
            log.info("参数非法或格式异常，openParam={}", openParam);
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        User user = userMapper.getUserByOpenId(openParam.getOpenid());
        return new RespEntity<User>(RespCode.SUCCESS, user);
    }

    @Override
    public RespEntity insertUser(User user) {
        if (Objects.isNull(user)) {
            log.info("参数非法或格式异常，user={}", user);
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        try {
            userMapper.insertUser(user);
        } catch (Exception e) {
            log.error("新增用户失败，user={}", user);
            return new RespEntity(RespCode.SERVER_ERROR);
        }
        return new RespEntity(RespCode.SUCCESS);
    }

    @Override
    public RespEntity updateUser(IntegralParam integralParam) {
        if (Objects.isNull(integralParam)) {
            log.info("参数非法或格式异常，integralParam={}", integralParam);
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }
        try {
            User user = userMapper.getUserByOpenId(integralParam.getOpenid());
            int integral = user.getIntegral() + integralParam.getNumber();
            user.setIntegral(integral);
            userMapper.updateUser(user);
            log.info("修改用户积分成功，integral={}", integral);
        } catch (Exception e) {
            return new RespEntity(RespCode.SERVER_ERROR, "修改用户积分失败");
        }
        return new RespEntity(RespCode.SUCCESS);
    }
}
